package com.masterclient.app.widget;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.LinearLayout;

import com.masterclient.app.R;
import com.eoner.baselibrary.utils.FastBlur;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：sean
 * 创建时间：2017/7/5 10:57
 * 功能说明：
 */

public class ProvinceTarget implements Target {
    private LinearLayout view;
    public ProvinceTarget(LinearLayout view) {
        this.view = view;
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Bitmap> e) throws Exception {
                e.onNext(blur(bitmap));
            }
        }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Bitmap>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull Bitmap bitmap) {
                view.postDelayed(()->{
                    view.setBackground(new BitmapDrawable(bitmap));
                },500);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                view.setBackgroundResource(R.mipmap.yindao4);
            }

            @Override
            public void onComplete() {
            }
        });

    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
    }

    private Bitmap blur(Bitmap bkg) {
        long startMs = System.currentTimeMillis();
        float scaleFactor = 16;
        float radius = 8;

        Bitmap overlay = Bitmap.createBitmap((int) (bkg.getWidth()/scaleFactor),
                (int) (bkg.getHeight()/scaleFactor), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
//        canvas.translate(0,0);
        canvas.scale(0.0625f, 0.0625f);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(bkg, 0, 0, paint);

        Paint paint1 = new Paint();
        paint1.setColor(0x88000000);
        canvas.drawRect(new Rect(0,0,bkg.getWidth(),bkg.getHeight()),paint1);

        overlay = FastBlur.doBlur(overlay, (int)radius, true);
        return overlay;

    }
}
